import {getLocalStorage} from "./util";
import {STORAGE_KEY} from "../config/constant";

let needLogin = [
	"/pages/login/login",
]

let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
list.forEach(item => {
	//用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
	uni.addInterceptor(item, {
		invoke(e) { // 调用前拦截
			//获取用户信息
			const userInfo = getLocalStorage(STORAGE_KEY.userInfo)
			//获取当前页面路径（即url去掉"?"和"?"后的参数）
			const url = e.url.split('?')[0]
			if (needLogin.includes(url) && !userInfo) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				}).then(() => {
				})
				uni.navigateTo({
					url: "/pages/login/login"
				}).then(() => {
				})
				return false
			}
			return true
		},
		fail(err) { // 失败回调拦截
			console.log(err);
		},
	})
})
